package com.srmt.document.feishu.internal.writer;

import com.lark.oapi.service.docx.v1.model.Block;
import com.srmt.document.exception.TableException;
import com.srmt.document.feishu.internal.core.BlockContext;
import com.srmt.feishu.client.FeishuClient;
import com.srmt.feishu.client.model.ProtectedDimension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Sheet保护操作服务
 * 处理电子表格的保护维度相关操作
 *
 * @author srmt
 * @since 3.0.0
 */
public class SheetProtectionService {

    private static final Logger logger = LoggerFactory.getLogger(SheetProtectionService.class);

    private final FeishuClient client;

    public SheetProtectionService(FeishuClient client) {
        this.client = client;
    }

    /**
     * 添加保护维度到Sheet
     *
     * @param docId 文档ID
     * @param tableAnchor 表格锚点
     * @param protectedDimensions 保护维度列表
     * @param userIdType 用户ID类型
     * @throws TableException 操作失败时抛出
     */
    public void addProtectedDimension(String docId, String tableAnchor,
                                     List<ProtectedDimension> protectedDimensions,
                                     String userIdType) throws TableException {
        logger.debug("向带有锚点的工作表添加保护维度 '{}' in document: {}", tableAnchor, docId);

        try {
            // 创建上下文
            BlockContext context = new BlockContext(client, docId);

            // 查找电子表格
            Block sheetBlock = context.findTableAfterAnchor(tableAnchor);
            if (sheetBlock == null) {
                throw new TableException("电子表格 未找到 after anchor: " + tableAnchor);
            }

            // 验证是否为Sheet类型
            if (sheetBlock.getBlockType() != 30 || sheetBlock.getSheet() == null) {
                throw new TableException("块 is not a 电子表格 type");
            }

            // 获取sheet token
            String sheetToken = sheetBlock.getSheet().getToken();
            if (sheetToken == null || sheetToken.isEmpty()) {
                throw new TableException("电子表格令牌为空");
            }

            logger.debug("找到工作表,令牌: {}", sheetToken);

            // 解析token
            String spreadsheetToken;
            String sheetId;
            int lastUnderscoreIndex = sheetToken.lastIndexOf('_');

            if (lastUnderscoreIndex == -1) {
                spreadsheetToken = sheetToken;
                sheetId = "";
            } else {
                spreadsheetToken = sheetToken.substring(0, lastUnderscoreIndex);
                sheetId = sheetToken.substring(lastUnderscoreIndex + 1);
            }

            logger.debug("解析电子表格令牌: {}, sheet ID: {}", spreadsheetToken, sheetId);

            // 如果sheetId为空，需要获取默认sheet的ID
            if (sheetId.isEmpty()) {
                // querySheets现在直接返回Sheet[]，失败时抛出FeishuApiException
                com.lark.oapi.service.sheets.v3.model.Sheet[] sheets =
                    client.sheets().querySheets(spreadsheetToken);

                if (sheets != null && sheets.length > 0) {
                    sheetId = sheets[0].getSheetId();
                    logger.debug("获取默认工作表ID: {}", sheetId);
                } else {
                    throw new TableException("无法确定电子表格的工作表ID: " + spreadsheetToken);
                }
            }

            // 更新保护维度中的sheetId
            for (ProtectedDimension pd : protectedDimensions) {
                if (pd.getDimension() != null) {
                    pd.getDimension().setSheetId(sheetId);
                }
            }

            // 调用Sheets API添加保护范围
            boolean success = client.sheets().addProtectedDimension(
                spreadsheetToken, protectedDimensions, userIdType);

            if (!success) {
                throw new TableException("向工作表添加保护维度失败");
            }

            logger.info("成功向工作表添加{}个保护维度", protectedDimensions.size());

        } catch (TableException e) {
            throw e;
        } catch (Exception e) {
            throw new TableException("添加保护维度失败: " + e.getMessage());
        }
    }
}
